package org.rqb.service;

import lombok.extern.slf4j.Slf4j;

import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.List;

@Slf4j
public class FileService {

    private static final int BUFFER_SIZE = 8192; // 8KB缓冲区

    public void readFileToText(String filePath, JTextArea textArea) {
        SwingUtilities.invokeLater(() -> textArea.setText(""));
        SwingWorker<Void, String> swingWorker = new SwingWorker<Void, String>() {
            @Override
            protected Void doInBackground() {
                try (BufferedReader reader = new BufferedReader(
                        new InputStreamReader(new FileInputStream(filePath), StandardCharsets.UTF_8))) {

                    char[] buffer = new char[BUFFER_SIZE];
                    int charsRead;
                    StringBuilder bufferStr = new StringBuilder();

                    while ((charsRead = reader.read(buffer)) != -1 && !isCancelled()) {
                        bufferStr.append(buffer, 0, charsRead);

                        // 每达到阈值时发布数据
                        if (bufferStr.length() >= BUFFER_SIZE * 5) {
                            publish(bufferStr.toString());
                            Thread.sleep(1000); //给UI线程一些缓冲时间，使得用户可以在间隔时间有操作
                            bufferStr.setLength(0); // 清空缓冲区
                        }
                    }

                    // 发布剩余数据
                    if (bufferStr.length() > 0) {
                        publish(bufferStr.toString());
                    }

                } catch (Exception e) {
                    // 错误处理...
                }
                return null;
            }

            @Override
            protected void process(List<String> chunks) {
                // 在 EDT 线程中安全更新 UI
                for (String text : chunks) {

                    textArea.setCaretPosition(0); // 将光标移到开头

                    textArea.append(text);
//                    textArea.scrollRectToVisible(new Rectangle(0, 0, 1, 1)); //保持一直在最上面
                }
            }

            @Override
            protected void done() {
                // 可选：读取完成后的处理
            }
        };
        swingWorker.execute();
    }
}